import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { User } from '@/modules/app/entities';
import { UserRelation } from './entities/user-relation.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RelationType } from './entities/user-relation.entity';
import { CreateUserRelationDto } from './dto/user-relation.dto';

@Injectable()
export class UserRelationService {
  constructor(
    @InjectRepository(UserRelation)
    private readonly userRelationRepository: Repository<UserRelation>,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  async createRelation(userId: number, data: CreateUserRelationDto) {
    const { toUserPhone, relationType } = data;
    const fromUser = await this.userRepository.findOne({
      where: { userId },
    });
    const toUser = await this.userRepository.findOne({
      where: { phone: toUserPhone },
    });

    if (!fromUser) {
      throw new HttpException('当前用户不存在', HttpStatus.BAD_REQUEST);
    }
    if (!toUser) {
      throw new HttpException('关联用户不存在', HttpStatus.BAD_REQUEST);
    }
    if (fromUser.role !== 'FAMILY') {
      throw new HttpException(
        '当前用户角色不是家属,无法关联',
        HttpStatus.BAD_REQUEST,
      );
    }
    if (toUser.role === 'FAMILY') {
      throw new HttpException(
        '目标用户角色是家属,无法关联',
        HttpStatus.BAD_REQUEST,
      );
    }

    // 检查关系是否已存在
    const existingRelation = await this.userRelationRepository.findOne({
      where: {
        fromUser: { userId },
        toUser: { phone: toUserPhone },
      },
    });

    if (existingRelation) {
      throw new HttpException('关联关系已存在', HttpStatus.BAD_REQUEST);
    }

    // 删除所有现有关系（双向）
    await this.userRelationRepository.delete({ fromUser: { userId } });

    // 创建新关系
    const relation = this.userRelationRepository.create({
      fromUser,
      toUser,
      relationType,
    });

    return this.userRelationRepository.save(relation);
  }
  /**
   * 获取用户的所有关系
   * @param userId 用户ID
   * @returns 用户的关系列表
   */
  async getUserRelations(userId: number): Promise<UserRelation[]> {
    const user = await this.userRepository.findOne({ where: { userId } });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }

    return this.userRelationRepository.find({
      where: [
        { fromUser: { userId }, isDeleted: false },
        { toUser: { userId }, isDeleted: false },
      ],
      relations: ['fromUser', 'toUser'],
    });
  }

  /**
   * 删除关系
   * @param userId 关系ID
   * @returns 删除结果
   */
  async deleteRelation(userId: number): Promise<void> {
    const relation = await this.userRelationRepository.findOne({
      where: { fromUser: { userId }, isDeleted: false },
    });
    if (!relation) {
      throw new HttpException('关系不存在', HttpStatus.BAD_REQUEST);
    }

    // 软删除
    relation.isDeleted = true;
    await this.userRelationRepository.save(relation);
  }

  /**
   * 更新关系类型
   * @param relationId 关系ID
   * @param relationType 新的关系类型
   * @returns 更新后的关系实体
   */
  async updateRelationType(
    relationId: number,
    relationType: RelationType,
  ): Promise<UserRelation> {
    const relation = await this.userRelationRepository.findOne({
      where: { relationId, isDeleted: false },
    });

    if (!relation) {
      throw new HttpException('关系不存在', HttpStatus.BAD_REQUEST);
    }

    relation.relationType = relationType;
    return this.userRelationRepository.save(relation);
  }
}
